#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/wait.h>
#define NUM 100
#define OPT_NUM 20
char LineCommand[NUM];
char* myargv[OPT_NUM];
int lastCode = 0;
int lastSig = 0;
int main()
{
    while(1)
    {
        lastCode = 0;
        lastSig = 0;
        //切割字符串
        printf("用户名@主机名 当前路径:");
        fflush(stdout);

        char* s = fgets(LineCommand, sizeof(LineCommand), stdin);
        assert(s != NULL);
        LineCommand[strlen(LineCommand) - 1] = '\0';
        myargv[0] = strtok(s, " ");
        int i = 1;
        if(myargv[0] != NULL && (strcmp(myargv[0], "ls") == 0))
        {
            myargv[i++] =(char*)"--color=auto";
        }
        while((myargv[i++] = strtok(NULL, " ")) != NULL);
        if(myargv[0] != NULL && (strcmp(myargv[0], "cd") == 0))
        {
            chdir(myargv[1]);
            continue;
        }
        if(myargv[0] != NULL && (strcmp(myargv[0], "echo") == 0))
        {
            if(strcmp(myargv[0], "echo") == 0)
            {
                printf("%d, %d\n", lastCode, lastSig);
            }
            else
            {
                printf("%s\n", myargv[1]);
            }
            continue;
        }
#ifdef DEBUG
   for(i = 0; myargv[i]; ++i)
   {
       printf("%s\n", myargv[i]);
   }
#endif

        //执行命令
        pid_t id = fork();
        if(id == 0)
        {
            execvp(myargv[0], myargv);
            exit(0);
        }
        int status = 0;
        int ret = waitpid(id, &status, 0);
        assert(ret > 0);
        lastCode = (status >> 8) & 0X7F;
        lastSig = status & 0XFF;
    }
    return 0;
}
